class WebSocketClient {
  constructor() {
    if (WebSocketClient.instance) return WebSocketClient.instance;
    WebSocketClient.instance = this;
    this.ws = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
  }

  connect(url) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) return;

    this.ws = new WebSocket(url);
    this.ws.onopen = () => {
      console.log("WebSocket connected");
      this.reconnectAttempts = 0; // 重置重连计数
    };
    this.ws.onmessage = (event) => {
      if (this.onMessageCallback) this.onMessageCallback(event.data);
    };
    this.ws.onclose = () => {
      console.log("WebSocket closed");
      this.handleReconnect(url); // 自动重连
    };
    this.ws.onerror = (error) => {
      console.error("WebSocket error:", error);
      this.handleReconnect(url);
    };
  }

  handleReconnect(url) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      setTimeout(() => {
        console.log(`Reconnecting... Attempt ${this.reconnectAttempts + 1}`);
        this.reconnectAttempts++;
        this.connect(url);
      }, this.reconnectInterval);
    }
  }

  send(message) {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(message);
    }
  }

  onMessage(callback) {
    this.onMessageCallback = callback;
  }

  close() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }
}

export default new WebSocketClient();